package com.javasm.adminapi.login.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.javasm.adminapi.common.Parameter;
import com.javasm.adminapi.common.R;
import com.javasm.adminapi.login.service.LoginService;
import com.javasm.adminapi.module.system.entity.User;
import com.javasm.adminapi.module.system.service.UserService;
import org.springframework.web.bind.annotation.*;
import com.google.code.kaptcha.util.Config;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

/**
 * @className: LoginController
 * @description:
 * @author: zcx
 * @date: 2025/10/15 10:21
 * @version: 0.1
 * @since: jdk17
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    LoginService loginService;

    @PostMapping("/json")
    public R jsonLogin(@RequestBody User loginUser){
        Parameter.check(loginUser);
        User user = loginService.login(loginUser);
        return R.ok(user);
    }


    @Resource
    HttpSession session;
    @Resource
    HttpServletResponse response;
    @GetMapping("/img/code")
    public void sendImgCode() throws IOException {
        //声明 生成验证码的配置对象
        Properties config = new Properties();
        //图片宽度
        config.setProperty("kaptcha.image.with","150");
        //高度
        config.setProperty("kaptcha.image.height","50");
        //随机数的范围
        config.setProperty("kaptcha.textproducer.char.string","0123456789");
        //验证码长度
        config.setProperty("kaptcha.textproducer.char.length","4");
        //配置对象，加入配置类
        Config kaptchaConfig = new Config(config);
        //创建图片对象
        DefaultKaptcha kapatcha = new DefaultKaptcha();
        //添加配置到图片对象
        kapatcha.setConfig(kaptchaConfig);
        //生成随机的字符串
        String code = kapatcha.createText();
        //code存入session等待调用
        session.setAttribute("json_code",code);
        //生成图片
        BufferedImage image = kapatcha.createImage(code);
        //写出去的头信息
        response.setContentType("image/jpeg");
        //流写出去
        ServletOutputStream outputStream = response.getOutputStream();
        //ImageIO对象写出去
        ImageIO.write(image,"jpg",outputStream);
    }


    //修改密码
    @PostMapping("/upload/info")
    public R uploadInfo(@RequestBody User user){
        loginService.uploadInfo(user);
        return R.ok();
    }
}
